package com.yan.comm;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

import com.yan.bean.Link;

public class MapUtils {

	public static <T> Map<String, Object> bean2Map(Object object) throws Exception {
		Map<String, Object> result = new HashMap<String, Object>();
		if (object == null) {
			return result;
		}
		@SuppressWarnings("unchecked")
		Class<T> cls = (Class<T>) object.getClass();
		Field[] fields = cls.getDeclaredFields();
		for (Field field : fields) {
			field.setAccessible(true);// 类中的成员变量为private,故必须进行此操作,否则异常
			if (field.getName().equalsIgnoreCase("serialVersionUID")) {
				continue;
			}
			result.put(field.getName(), field.get(object));
		}
		return result;
	}

	public static <T> Object map2Bean(Map<String, Object> map, Class<T> cls) throws Exception {
		Object object = cls.newInstance();
		for (String key : map.keySet()) {
			Field temFiels = cls.getDeclaredField(key);
			temFiels.setAccessible(true);
			temFiels.set(object, map.get(key));
		}
		return object;
	}

	public static void main(String args[]) throws Exception {
		Link link = new Link();
		link.setId(1);
		link.setLinkName("linkName");
		System.out.println(link);
		bean2Map(link);
		System.out.println(bean2Map(link));
		System.out.println(map2Bean(bean2Map(link), Link.class));

	}
}
